package com.dily.study.user.config;

import com.dily.scaffold.context.security.JwtProperties;
import com.dily.study.user.filter.JwtAuthenticationFilter;
import com.dily.study.user.handle.AuthenticationHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Date: 2022-06-09 星期四
 * Time: 17:24
 * Author: Dily_Su
 * Remark:
 */
@EnableConfigurationProperties(JwtProperties.class)
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {
    /**
     * 不走security的url地址，antPatterns 格式{@link org.springframework.security.web.util.matcher.AntPathRequestMatcher}
     */
    public static final String[] BYPASS_PATTERNS = {
            "/user/login",
            "/session/*", // session是token校验，token刷新，登出接口
    };

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http    // 允许跨域
                .cors()
                .and()
                //关闭 csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers(BYPASS_PATTERNS).anonymous()
                .antMatchers("/user/delete").hasAuthority("system")
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();
        // 指定 插入 fitter 位置
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        // 认证失败处理器
        http.exceptionHandling()
                // 认证失败处理器
                .authenticationEntryPoint(new AuthenticationHandle())
                // 授权失败处理器
                .accessDeniedHandler(new AuthenticationHandle());

        //  用于原生 SpringSecurity，有 UserPasswordFilter 的时候
//        http.formLogin() // 配置 UserPasswordFilter
//                .successHandler(new DemoAuthenticationHandler());  // 自定义 的 AuthenticationHandler
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 跨域配置
     * 需要实现 WebMvcConfigurer
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 设置允许跨域的路径
        registry.addMapping("/**")
                // 设置允许跨域请求的域名
//                .allowedOriginPatterns("*")
                // 是否允许cookie
                .allowCredentials(true)
                // 设置允许的请求方式
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                // 设置允许的header属性
                .allowedHeaders("*")
                // 跨域允许时间
                .maxAge(3600);
    }
}
